﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Jive.Helpers;
using Jive.Models;
using Jive.Settings;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Jive.ViewModels
{
    public class ViewModelGetEmoticonsPage : ViewModelBase
    {
        public ObservableCollection<string> EmoticonUsers { get; set; }
        public ObservableCollection<AddEmoticonModel> UserEmoticons { get; set; }
        public RelayCommand<SelectionChangedEventArgs> UserChangedCommand { get; private set; }
        public RelayCommand<AddEmoticonModel> ShortcutChangedCommand { get; private set; }
        public RelayCommand AddEmoticonsCommand { get; private set; }
        public RelayCommand<string> LoadUserCommand { get; private set; }

        private string _selectedEmoticonUser;
        public string SelectedEmoticonUser
        {
            get { return _selectedEmoticonUser; }
            set
            {
                if (_selectedEmoticonUser != value)
                {
                    _selectedEmoticonUser = value;
                    RaisePropertyChanged("SelectedEmoticonUser");
                }
            }
        }


        public ViewModelGetEmoticonsPage()
        {
            AddEmoticonsCommand = new RelayCommand(AddEmoticons);
            UserEmoticons = new ObservableCollection<AddEmoticonModel>();
            UserChangedCommand = new RelayCommand<SelectionChangedEventArgs>(UserChanged);
            ShortcutChangedCommand = new RelayCommand<AddEmoticonModel>(ShortcutChanged);
            LoadUserCommand = new RelayCommand<string>(LoadUserCommandAction);
            if (DesignerProperties.IsInDesignTool)
                return;
            this.EmoticonUsers = CreateUserList(AppSettings.AppSettingsInstance.CustomContactEmoticons);
        }

        private void LoadUserCommandAction(string loadedUserID)
        {
            this.SelectedEmoticonUser = loadedUserID;
            if (AppSettings.AppSettingsInstance.CustomContactEmoticons.ContainsKey(loadedUserID))
                CreateEmoticonList(AppSettings.AppSettingsInstance.CustomContactEmoticons[loadedUserID]);

        }

        private void AddEmoticons()
        {
            if (this.UserEmoticons.Count == 0)
                return;

            foreach (AddEmoticonModel emo in this.UserEmoticons)
            {
                if (!emo.IsChecked)
                    continue;

                String text = (string)emo.EmoticonShortcut;

                try
                {
                    BitmapImage emoticonImage = StaticMethods.LoadBitmapImageFromIsolatedStorage(emo.EmoticonPath);
                    if (emoticonImage == null)
                        continue;
                    string savePath = StaticMethods.CombinePath(StaticSettings.CustomEmoticonFolder, emo.EmoticonPath.Substring(emo.EmoticonPath.LastIndexOf(@"\")).Replace(@"\", ""));
                    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!storage.DirectoryExists(StaticSettings.CustomEmoticonFolder))
                            storage.CreateDirectory(StaticSettings.CustomEmoticonFolder);
                    }
                    StaticMethods.SaveToPng(emoticonImage, savePath);
                    StaticSettings.CustomEmoticons.Add(text, savePath);
                    ShortcutChanged(emo);
                    Jive.CustomControls.EmoticonControl.NeedRefresh = true;
                }
                catch (Exception err)
                {
                    Messenger.Default.Send(err.Message);
                }
            }
            CreateEmoticonList(AppSettings.AppSettingsInstance.CustomContactEmoticons[this.SelectedEmoticonUser]);
        }

        private void ShortcutChanged(AddEmoticonModel model)
        {
            string error;
            bool valid = StaticMethods.ValidateEmoticonShortcut((string)model.EmoticonShortcut, out error);
            model.IsChecked = valid;
        }

        private void UserChanged(SelectionChangedEventArgs args)
        {
            string userID = (string)args.AddedItems[0];
            CreateEmoticonList(AppSettings.AppSettingsInstance.CustomContactEmoticons[userID]);
        }

        private void CreateEmoticonList(Dictionary<string, string> dictionary)
        {
            UserEmoticons.Clear();
            foreach (KeyValuePair<string, string> kvp in dictionary)
            {
                AddEmoticonModel model = new AddEmoticonModel() { EmoticonPath = kvp.Value, EmoticonShortcut = kvp.Key, EmoticonType = EmoticonType.CustomEmoticon };
                ShortcutChanged(model);
                UserEmoticons.Add(model);
            }
        }

        private ObservableCollection<string> CreateUserList(Dictionary<string, Dictionary<string, string>> userEmoticons)
        {

            ObservableCollection<string> users = new ObservableCollection<string>();
            foreach (KeyValuePair<string, Dictionary<string, string>> kvp in userEmoticons)
            {
                users.Add(kvp.Key);

            }
            return users;
        }
    }
}
